package com.example.controller;
import com.example.service.ActivityService;
import com.example.entity.Activity;
import com.example.entity.Organization;
import com.example.entity.Users;
import com.example.service.OrganizationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 组织管理控制器
 * 处理组织相关的CRUD操作和搜索功能
 * 基础路径：/organization
 */
@Controller
@RequestMapping("/organization")
public class OrganizationController {

    @Autowired
    private OrganizationService organizationService; // 注入组织服务
private final ActivityService activityService;
 @Autowired
    public OrganizationController(OrganizationService organizationService,
                                  ActivityService activityService) {
        this.organizationService = organizationService;
        this.activityService = activityService;
    }
    /**
     * 获取所有组织列表
     * @param model 用于向视图传递数据的模型对象
     * @return 返回组织列表视图路径
     */
    @GetMapping("/list")
    public String list(Model model) {
        // 获取所有组织信息
        List<Organization> organization = organizationService.getAllOrganizations();
        // 将组织列表添加到模型
        model.addAttribute("organization", organization);
        // 返回组织列表页面
        return "organization/list";
    }

    /**
     * 跳转到添加组织页面
     * @return 返回添加组织表单视图路径
     */
    @GetMapping("/add")
    public String toAddPage() {
        return "organization/add";
    }

    /**
     * 添加新组织
     * @param organization 表单提交的组织数据
     * @param userid 关联用户ID
     * @return 重定向到组织列表页
     */
    @PostMapping("/add")
    public String add(Organization organization, int userid) {
        // 设置关联用户
        Users users = new Users();
        users.setUserid(userid);
        organization.setUsers(users);
        // 保存组织信息
        organizationService.addOrganization(organization);
        // 重定向到组织列表
        return "redirect:/organization/list";
    }

    /**
     * 跳转到编辑组织页面
     * @param orgid 组织ID
     * @param model 用于向视图传递数据的模型对象
     * @return 返回组织编辑表单视图路径
     */
    @GetMapping("/edit/{orgid}")
    public String toEditPage(@PathVariable("orgid") Integer orgid, Model model) {
        // 根据ID获取组织信息
        Organization organization = organizationService.getOrganizationByOrgid(orgid);
        // 将组织信息添加到模型
        model.addAttribute("organization", organization);
        // 返回编辑页面
        return "organization/edit";
    }

    /**
     * 更新组织信息
     * @param organization 表单提交的组织数据
     * @return 重定向到组织列表页
     */
    @PostMapping("/edit")
    public String edit(Organization organization) {
        // 更新组织信息
        organizationService.updateOrganization(organization);
        // 重定向到组织列表
        return "redirect:/organization/list";
    }

    /**
     * 删除组织
     * @param orgid 要删除的组织ID
     * @return 重定向到组织列表页
     */
    @GetMapping("/delete/{orgid}")
    public String delete(@PathVariable("orgid") Integer orgid) {
        // 删除指定ID的组织
        organizationService.deleteOrganization(orgid);
        // 重定向到组织列表
        return "redirect:/organization/list";
    }

    /**
     * 搜索组织
     * @param org_name 组织名称(可选)
     * @param org_type 组织类型(可选)
     * @param model 用于向视图传递数据的模型对象
     * @return 返回组织列表视图路径(包含搜索结果)
     */
    @GetMapping("/search")
    public String searchOrganization(
            @RequestParam(required = false) String org_name,
            @RequestParam(required = false) String org_type,
            Model model) {

        List<Organization> organization;
        // 检查是否有搜索条件
        if (StringUtils.hasText(org_name) || StringUtils.hasText(org_type)) {
            // 执行条件搜索
            organization = organizationService.searchOrganizations(org_name, org_type);
        } else {
            // 无搜索条件时获取全部组织
            organization = organizationService.getAllOrganizations();
        }

        // 将搜索结果和搜索条件添加到模型
        model.addAttribute("organization", organization);
        model.addAttribute("org_name", org_name);
        model.addAttribute("org_type", org_type);

        // 返回组织列表页面(显示搜索结果)
        return "organization/list";
    }
    
    /**
     * 机构首页
     */
    @GetMapping("/home")
    public String showHome(HttpSession session, Model model) {
        Users user = (Users) session.getAttribute("users");
        if (user == null || !"organization".equals(user.getUsertype())) {
            return "redirect:/users/login";
        }

        Organizations org = organizationService.getOrganizationByUserId(user.getUserid());
        int activityCount = activityService.countActivitiesByOrgId(org.getOrgid()); // 获取活动总数

        model.addAttribute("organizations", org); // 添加机构信息到模型
        model.addAttribute("activityCount", activityCount); // 添加活动数量到模型

        return "forward:/WEB-INF/views/organization/home.jsp"; // 转发到 home.jsp 页面
    }
     @GetMapping("/guanli")
    public String showActivityManagement(HttpSession session, Model model) {
        Users user = (Users) session.getAttribute("users");
        if (user == null || !"organization".equals(user.getUsertype())) {
            return "redirect:/users/login"; // 如果未登录或不是机构用户，跳转到登录页
        }

        Organizations org = organizationService.getOrganizationByUserId(user.getUserid()); // 根据用户 ID 获取机构信息

        List<Activity> allActivities = activityService.getAllActivitiesByOrgId(org.getOrgid()); // 所有活动
        List<Activity> ongoingActivities = activityService.getOngoingActivitiesByOrgId(org.getOrgid()); // 进行中的活动
        List<Activity> upcomingActivities = activityService.getUpcomingActivitiesByOrgId(org.getOrgid()); // 即将开始的活动
        List<Activity> completedActivities = activityService.getCompletedActivitiesByOrgId(org.getOrgid()); // 已完成的活动

        System.out.println("All Activity: " + allActivities); // 调试输出

        // 将数据放入模型中供 JSP 页面使用
        model.addAttribute("organizations", org);
        model.addAttribute("activities", allActivities);
        model.addAttribute("ongoingActivitiesList", ongoingActivities);
        model.addAttribute("upcomingActivitiesList", upcomingActivities);
        model.addAttribute("completedActivitiesList", completedActivities);
        model.addAttribute("totalActivities", allActivities.size());
        model.addAttribute("ongoingActivities", ongoingActivities.size());
        model.addAttribute("upcomingActivities", upcomingActivities.size());
        model.addAttribute("completedActivities", completedActivities.size());

        return "forward:/WEB-INF/views/organization/guanli.jsp"; // 转发到 guanli.jsp 页面
    }

    @PostMapping("/updateActivity")
    public String updateActivity(@RequestBody Activity activity) {
        System.out.println("接收到的要更新的活动: " + activity);
        activityService.updateActivity(activity);
        return "redirect:/organization/guanli";
    }

    @GetMapping("/profile")
    public String viewProfile(HttpSession session, Model model) {
        Users user = (Users) session.getAttribute("users");
        if (user == null || !"organization".equals(user.getUsertype())) {
            return "redirect:/users/login"; // 非机构用户跳转登录
        }

        Organizations org = organizationService.getOrganizationByUserId(user.getUserid());
        int activityCount = activityService.countActivitiesByOrgId(org.getOrgid()); // 活动数量
        int serviceHours = activityService.getTotalServiceHours(org.getOrgid()); // 总服务时长

        model.addAttribute("organizations", org); // 添加机构信息
        model.addAttribute("activityCount", activityCount); // 添加活动数量
        model.addAttribute("serviceHours", serviceHours); // 添加服务时长

        return "forward:/WEB-INF/views/organization/profile.jsp"; // 转发到 profile.jsp 页面
    }

    /**
     * 显示更新机构资料的表单。
     */
    @GetMapping("/updateProfile")
    public String showUpdateForm(HttpSession session, Model model) {
        Users user = (Users) session.getAttribute("users");
        if (user == null || !"organization".equals(user.getUsertype())) {
            return "redirect:/users/login";
        }

        Organizations org = organizationService.getOrganizationByUserId(user.getUserid());
        model.addAttribute("organizations", org); // 添加机构信息供表单显示

        return "forward:/WEB-INF/views/organization/updateProfile.jsp"; // 转发到 updateProfile.jsp 页面
    }

    /**
     * 处理更新机构资料的请求。
     */
    @PostMapping("/updateProfile")
    public String updateProfile(
            @RequestParam String org_name,
            @RequestParam String contact_phone,
            @RequestParam String address,
            @RequestParam String description,
            HttpSession session) {

        Users user = (Users) session.getAttribute("users");
        if (user == null || !"organization".equals(user.getUsertype())) {
            return "redirect:/users/login";
        }

        // 从数据库获取最新数据
        Organizations org = organizationService.getOrganizationByUserId(user.getUserid());

        // 更新非空字段
        if (org_name != null && !org_name.isEmpty()) {
            org.setOrgName(org_name);
        }
        if (contact_phone != null && !contact_phone.isEmpty()) {
            org.setContactPhone(contact_phone);
        }
        if (address != null && !address.isEmpty()) {
            org.setAddress(address);
        }
        if (description != null && !description.isEmpty()) {
            org.setDescription(description);
        }

        // 更新数据库
        organizationService.updateOrganization(org);

        // 更新 Session 数据
        session.setAttribute("organizations", org);

        return "redirect:/organization/profile"; // 跳转到详情页
    }
 @GetMapping("/getCurrentUser")
    public @ResponseBody Organizations getCurrentOrganization(HttpSession session) {
        Users user = (Users) session.getAttribute("users");
        if (user == null || !"organization".equals(user.getUsertype())) {
            return null;
        }
        return organizationService.getOrganizationByUserId(user.getUserid()); // 返回机构对象
    }
}